package com.openatc.optimize.fixedtimeplan.config.cross;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author mz
 * @version 1.0
 * @date 2021/8/20 14:34
 */
@Data
@NoArgsConstructor
@Builder
@AllArgsConstructor

public class CrossConfig {
    private String type;
    private long optcycle;
    private String name;
    private String agentid;
    private int red = 2;
    private int yellow = 3;
    private List<Ring> rings;
    private int loss = 3;
    private List<Barrier> barriers;
    private List<Phase> phases;


    //兼容处理
    private List<Phase> phaseList;
    private PatternFeature pattern;


    public void init(){
        if(rings != null){
            return;
        }
        barriers = createBarriers();
        rings = createRings();

        updatephases();

    }



    private Phase phasebyid(int id){
        for(Phase phase:phases){
            if(phase.getId() == id){
                return phase;
            }
        }
        return null;
    }


    private List<Ring> createRings(){
        List<Ring> optrings = new LinkedList<>();

        List<List<PatternPhase>> rings = pattern.getRings();
        for(int i=0; i < rings.size(); i++){
            List<PatternPhase> patternPhases = rings.get(i);
            List<Integer> sequence = new LinkedList<>();
            for(PatternPhase patternPhase:patternPhases){
                sequence.add(patternPhase.getId());
            }
            if(sequence.size() > 1){
                Ring ring = Ring.builder().sequence(sequence).num(i+1).build();
                optrings.add(ring);
            }

        }

        return optrings;
    }


    private List<Barrier> createBarriers(){
        List<BarrierFeature> barrierFeatures = pattern.getBarriers();
        List<Barrier> optbarriers = new LinkedList<>();
        for(BarrierFeature barrierFeature : barrierFeatures){
            Barrier barrier = Barrier.createBarrierByBarrierFeature(barrierFeature);
            optbarriers.add(barrier);
        }
        return optbarriers;
    }


    private void updatephases(){
        for(List<PatternPhase> patternPhases : pattern.getRings()){
            for(PatternPhase patternPhase : patternPhases){
                int phaseId = patternPhase.getId();
                long duration = patternPhase.getValue();
                Phase phase = phasebyid(phaseId);
                if(phase != null){
                    phase.setDuration(duration);
                }


            }
        }


        for(Phase phase:phaseList){
            int phaseId = phase.getId();
            Phase targetphase = phasebyid(phaseId);
            if(targetphase != null){
                targetphase.setMingreen(phase.getMingreen());
                targetphase.setMaxgreen(phase.getMax1());
            }

        }


    }


}
